const express = require("express");
const router = express.Router();
const utils = require("../../utils/index.js");
const {systemSettings} =require("../../utils/menuString");
const pools = require("../../utils/pools.js");
const svgCaptcha = require('svg-captcha');
const pool = require('../../pool.js');

//添加商品
router.post("/addProduct", async (req, res) => {
    let sql = "INSERT INTO product(name,cagegory_id,price,desr,img_url,cuxiao_price,vip_price) VALUES (?,?,?,?,?,?,?)", obj = req.body;
    await pools({sql,val:[obj.name,obj.cagegoryId,obj.price,obj.desr,obj.imgUrl,obj.cuxiaoPrice,obj.vipPrice],res,req,run:false});
});

//修改商品（库存）
router.post("/updateProduct", async (req, res) => {
    let sql = "UPDATE  product SET name=?,cagegory_id=?,desr=?,price=? ,img_url=? ,cuxiao_price=?,vip_price=? WHERE id=?", obj = req.body;
    await pools({sql,val:[obj.name, obj.cagegoryId, obj.desr, obj.price, obj.imgUrl,obj.cuxiaoPrice,obj.vipPrice,obj.id],res,req,run:false});
});

//修改库存
router.post("/editProductStoreNum", async (req, res) => {
    let sql = "UPDATE  product SET store_num=? WHERE id=?", obj = req.body;
    await pools({sql,val:[obj.storeNum,obj.id],res,req,run:false});
});
//查询商品（或者库存）
router.post("/getProductList", async (req, res) => {
    let obj=req.body;
    let sql = `SELECT id AS id,name AS name,cagegory_id AS cagegoryId,price AS price,desr AS desr,img_url AS imgUrl,store_num as storeNum,create_time AS createTime ,cuxiao_price as cuxiaoPrice,vip_price as vipPrice FROM product WHERE 1=1`;
    sql=utils.setLike(sql,"name",obj.name);
    sql=utils.setAssign(sql,"cagegory_id",obj.cagegoryId);
    sql=utils.setAssign(sql,"id",obj.id);
    let {total}=await utils.getSum({sql,name:"product",res,req});
    sql+=` ORDER BY id desc`;
    sql=utils.pageSize(sql,obj.page,obj.size);
    let {result}=await pools({sql,res,req});
    res.send(utils.returnData({data: result,total}));
});

//删除商品信息（或者库存）
router.post("/delProduct", async (req, res) => {
    let sql = "DELETE FROM product WHERE id=?", obj = req.body;
    await pools({sql,val:[obj.id],res,req,run:false});
});


//查询订单（或者库存）
router.post("/getProductOrderList", async (req, res) => {
    let obj=req.body;
    let sql = `select B.id as id,B.num ,B.product_name as productName,B.price,B.create_time as createTime,B.totalPay,B.order_status as status,B.address,C.id as productId,C.img_url as imgUrl,C.\`name\` as productName,D.name as providerName from order_pro B left JOIN product C on B.product_id=C.id left join provider D on B.provider_id=D.id WHERE 1=1`;
    sql=utils.setLike(sql,"product_name",obj.name);
    sql=utils.setAssign(sql,"order_status",obj.status);
    let {total}=await utils.getSum({sql,name:"order_pro",res,req});
    sql+=` ORDER BY B.id desc`;
    sql=utils.pageSize(sql,obj.page,obj.size);
    let {result}=await pools({sql,res,req});
    res.send(utils.returnData({data: result,total}));
});
//新增订单（）
router.post("/addProductOrder", async (req, res) => {
    var obj = req.body
    var totalPay =parseFloat(obj.price)*parseFloat(obj.num);
    let sql = "INSERT INTO `vue_admin`.`order_pro` (`product_id`, `product_name`, `num`,  `address`, `provider_id`, `totalPay`,`price`) VALUES (?,?,?,?,?,?,?)";
    await pools({sql,val:[obj.productId,obj.productName,obj.num,obj.address,obj.providerId,totalPay,obj.price],res,req,run:false});
});

//修改订单（）
router.post("/updateProductOrder", async (req, res) =>{
    let obj = req.body
    if(!obj.id){
        res.send(utils.returnData({code: -1, msg: "请选择要修改的数据！",req}));
    }
    var totalPay =parseFloat(obj.price)*parseFloat(obj.num);
    let sql = "update order_pro set num = ?,order_status=?,address=?,totalPay=?,price=? where id=?";
    await pools({sql,val:[obj.num,obj.status,obj.address,totalPay,obj.price,obj.id],res,req,run:false});
});
//删除订单（）
router.post("/delProductOrder", async (req, res) =>{
    let sql = `delete from  order_pro  where id = ?`;
    let obj = req.body;
    if(!obj.id){
        res.send(utils.returnData({code: -1, msg: "请选择要删除的数据！",req}));
    }
    await pools({sql,val:[obj.id],res,req,run:false});
});

//查询供应商列表信息
router.post("/getProviderList", async (req, res) => {
    let obj=req.body;
    let sql = `select B.id,B.name,B.status,B.address,B.phone,B.category_id as categoryId,B.create_time as createTime  from provider B WHERE 1=1`;
    sql=utils.setLike(sql,"name",obj.name);
    sql=utils.setAssign(sql,"category_id",obj.categoryId);
    sql=utils.setAssign(sql,"status",obj.status);
    let {total}=await utils.getSum({sql,name:"provider",res,req});
    sql+=` ORDER BY B.id desc`;
    sql=utils.pageSize(sql,obj.page,obj.size);
    let {result}=await pools({sql,res,req});
    res.send(utils.returnData({data: result,total}));
});

//修改供应商信息
router.post("/updateProvider", async (req, res) => {
    let obj=req.body;
    if(!obj.id){
        res.send(utils.returnData({code: -1, msg: "请选择要修改的数据！",req}));
    }
    let sql = "UPDATE  provider SET name=?,phone=?,status=?,address=?,category_id=? WHERE id=?";
    await pools({sql,val:[obj.name,obj.phone,obj.status,obj.address,obj.categoryId,obj.id],res,req,run:false});
});

//新增供应商信息
router.post("/addProvider", async (req, res) => {
    let obj=req.body;

    let sql = "INSERT INTO `vue_admin`.`provider` ( `name`, `phone`,  `status`, `address`, `category_id`) VALUES (?,?,?,?,?)";
    await pools({sql,val:[obj.name,obj.phone,obj.status,obj.address,obj.categoryId],res,req,run:false});
});

//删除供应商信息
router.post("/delProvider", async (req, res) => {
    let sql = `delete from  provider  where id = ?`;
    let obj = req.body;
    if(!obj.id){
        res.send(utils.returnData({code: -1, msg: "请选择要删除的数据！",req}));
    }
    await pools({sql,val:[obj.id],res,req,run:false});

});

//查询商品分类信息
router.post("/getProductCategoryList", async (req, res) => {
    let obj=req.body;
    let sql = `select B.id ,B.level_id as levelId,B.parent_id as parentId,B.name,B.parent_name as parentName,B.create_time as createTime  from product_category B where 1=1`;
    sql=utils.setLike(sql,"name",obj.name);
    sql=utils.setAssign(sql,"level_id",obj.levelId);
    let {total}=await utils.getSum({sql,name:"product_category",res,req});
    sql+=` ORDER BY B.id desc`;
    sql=utils.pageSize(sql,obj.page,obj.size);
    let {result}=await pools({sql,res,req});
    res.send(utils.returnData({data: result,total}));
});
//修改商品分类信息（只能修改名称）
router.post("/updateProductCategory", async (req, res) => {
    let sql = "UPDATE  product_category SET name=? WHERE id=?", obj = req.body;
    await pools({sql,val:[obj.name,obj.id],res,req,run:false});
});

//新增商品分类信息（只能新增名称不存在的）
router.post("/addProductCategory", async (req, res) => {
    let sql = `select B.id ,B.level_id as levelId,B.parent_id as parentId,B.name  from product_category B where 1=1`;
    let obj = req.body;
    sql=utils.setAssign(sql,"name",'\''+obj.name+'\'');
    let {result}=await pools({sql,res,req});
    if(result.length>0){
        var data = {"test":1};
        res.send(utils.returnData({code: -1, msg: "分类名称已存在！",data}));
    }else{
        if(obj.levelId==1){
            obj.parentId=0;
            sql = "INSERT INTO `vue_admin`.`product_category` ( `level_id`, `parent_id`, `name`)  VALUES (?,?,?)";
            await pools({sql,val:[obj.levelId,obj.parentId,obj.name],res,req,run:false});
        }else{
            //查询父级分类名称
            sql = `select B.id ,B.name  from product_category B where 1=1 `;
            sql=utils.setAssign(sql,"id",obj.parentId);
            result = await pools({sql,res,req});
            sql = "INSERT INTO `vue_admin`.`product_category` ( `level_id`, `parent_id`, `name`, `parent_name`)  VALUES (?,?,?,?)";
            await pools({sql,val:[obj.levelId,obj.parentId,obj.name,result['result'][0].name],res,req,run:false});
        }

    }
});

//删除商品分类信息（如果是删除的一级分类，那么下面的所有关联的二级分类也一起删除掉）
router.post("/delProductCategory", async (req, res) => {
    let sql = `delete from  product_category  where id = ? or parent_id=?`;
    let obj = req.body;
    await pools({sql,val:[obj.id,obj.id],res,req,run:false});
});








module.exports = router;
